package com.sheliduan.itlearning.common.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sheliduan.itlearning.common.aspect.ApiOperationLog;
import com.sheliduan.itlearning.common.aspect.AuthAccess;
import com.sheliduan.itlearning.common.domain.dos.ArticleCourseDO;
import com.sheliduan.itlearning.common.domain.dos.OrderDO;
import com.sheliduan.itlearning.common.domain.dos.UserBoughtCourseDO;
import com.sheliduan.itlearning.common.domain.dos.VideoCourseDO;
import com.sheliduan.itlearning.common.domain.mapper.*;
import com.sheliduan.itlearning.common.enums.ErrorCodeEnum;
import com.sheliduan.itlearning.common.model.vos.*;
import com.sheliduan.itlearning.common.utils.PageResponseData;
import com.sheliduan.itlearning.common.utils.ResponseData;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 断舍离
 * @date: 2025/4/16 10:08
 * @description: 支付/订单功能相关控制器
 **/
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserBoughtCourseMapper userBoughtCourseMapper;

    @Autowired
    private ArticleCourseMapper articleCourseMapper;

    @Autowired
    private VideoCourseMapper videoCourseMapper;

    @Autowired
    private UserMapper userMapper;

    @PostMapping("/add")
    @ApiOperationLog(description = "下单")
    public ResponseData addOrder(@RequestBody @Validated AddOrderReqVO reqVO) {
        LambdaQueryWrapper<OrderDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(OrderDO::getCourseId, reqVO.getCourseId());
        wrapper.eq(OrderDO::getUserId, reqVO.getUserId());
        wrapper.eq(OrderDO::getType, reqVO.getType());
        OrderDO order = orderMapper.selectOne(wrapper);
        // 说明该用户已经对该课程下过单了，给出提示
        if(order != null) {
            return ResponseData.fail(ErrorCodeEnum.ORDER_IS_EXIST);
        }
        OrderDO orderDO = new OrderDO();
        BeanUtils.copyProperties(reqVO, orderDO);
        // 设置状态为待支付
        orderDO.setStatus(0);
        orderMapper.insert(orderDO);
        return ResponseData.success();
    }

    @PostMapping("/pageList")
    @ApiOperationLog(description = "订单分页列表")
    public PageResponseData findOrderPageList(@RequestBody @Validated FindOrderPageListReqVO reqVO){
        long current = reqVO.getCurrent();
        long size = reqVO.getSize();
        Integer userId = reqVO.getUserId();
        Page<OrderDO> page = orderMapper.selectPageList(current, size, userId);
        List<OrderDO> orderDOS = page.getRecords();
        List<FindOrderPageListRspVO> vos = new ArrayList<>();
        if(!CollectionUtils.isEmpty(orderDOS)) {
            vos = orderDOS.stream().map(orderDO -> {
                FindOrderPageListRspVO vo = new FindOrderPageListRspVO();
                Integer type = orderDO.getType();
                Integer courseId = orderDO.getCourseId();
                ArticleCourseDO articleCourseDO = articleCourseMapper.selectById(courseId);
                VideoCourseDO videoCourseDO = videoCourseMapper.selectById(courseId);
                String title;
                String cover;
                if(type == 0) {
                    title = articleCourseDO.getTitle();
                    cover = articleCourseDO.getCover();
                }else {
                    title = videoCourseDO.getTitle();
                    cover = videoCourseDO.getCover();
                }
                vo.setId(orderDO.getId());
                vo.setTitle(title);
                vo.setCover(cover);
                vo.setNumber(orderDO.getNumber());
                vo.setPrice(orderDO.getPrice());
                vo.setUsername(userMapper.selectById(userId).getUsername());
                vo.setStatus(orderDO.getStatus());
                vo.setOrderTime(orderDO.getOrderTime());
                return vo;
            }).collect(Collectors.toList());
        }
        return PageResponseData.success(page, vos);
    }

    @PostMapping("/changeOrderStatus")
    @ApiOperationLog(description = "更改订单状态")
    public ResponseData changeOrderStatus(@RequestBody @Validated ChangeOrderStatusReqVO reqVO) {
        // 说明是取消订单，删除该订单
        if(reqVO.getStatus() == 2) {
            orderMapper.deleteById(reqVO.getId());
            return ResponseData.success();
        }
        OrderDO orderDO = new OrderDO();
        orderDO.setId(reqVO.getId());
        orderDO.setStatus(reqVO.getStatus());
        orderMapper.updateById(orderDO);
        // 说明是支付购买请求, 往用户已购课程表加入一条数据
        if(reqVO.getStatus() == 1) {
            UserBoughtCourseDO userBoughtCourseDO = new UserBoughtCourseDO();
            orderDO = orderMapper.selectById(reqVO.getId());
            if(orderDO.getType() == 0) {
                ArticleCourseDO articleCourseDO = articleCourseMapper.selectById(orderDO.getCourseId());
                userBoughtCourseDO.setBloggerId(articleCourseDO.getUserId());
            }else {
                VideoCourseDO videoCourseDO = videoCourseMapper.selectById(orderDO.getCourseId());
                userBoughtCourseDO.setBloggerId(videoCourseDO.getUserId());
            }
            userBoughtCourseDO.setCourseId(orderDO.getCourseId());
            userBoughtCourseDO.setOrderTime(orderDO.getOrderTime());
            userBoughtCourseDO.setType(orderDO.getType());
            userBoughtCourseDO.setUserId(orderDO.getUserId());
            userBoughtCourseMapper.insert(userBoughtCourseDO);
        }
        return ResponseData.success();
    }

}
